/**
 * Copyright 2018 人人开源 http://www.renren.io
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.hs.srm.admin.modules.sys.controller;

import java.util.*;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.hs.srm.base.common.annotation.SysLog;
import com.hs.srm.base.common.utils.Constant;
import com.hs.srm.base.modules.sys.entity.SysDeptEntity;
import com.hs.srm.base.modules.sys.entity.SysMenuEntity;
import com.hs.srm.base.modules.sys.entity.SysRoleEntity;
import com.hs.srm.base.modules.sys.service.SysDeptService;
import com.hs.srm.base.modules.sys.service.SysMenuService;
import com.hs.srm.base.modules.sys.service.SysRoleDeptService;
import com.hs.srm.base.modules.sys.service.SysRoleMenuService;
import com.hs.srm.base.modules.sys.service.SysRoleService;
import com.hs.srm.common.utils.PageUtils;
import com.hs.srm.common.utils.R;
import com.hs.srm.common.validator.ValidatorUtils;

/**
 * 角色管理
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年11月8日 下午2:18:33
 */
@RestController
@RequestMapping("/sys/role")
public class SysRoleController extends AbstractController {
    private static final long serialVersionUID = -9186309154482271627L;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    @Autowired
    private SysRoleDeptService sysRoleDeptService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysMenuService sysMenuService;

    /**
     * 删除角色
     */
    @SysLog("删除角色")
    @RequestMapping("/delete")
    @RequiresPermissions("sys:role:delete")
    public R delete(@RequestParam(value = "roleIds[]") Long[] roleIds) {
        this.sysRoleService.deleteBatch(roleIds);
        return R.ok();
    }

    /**
     * 角色信息
     */
    @RequestMapping("/info/{roleId}")
    @RequiresPermissions("sys:role:info")
    public R info(@PathVariable("roleId") Long roleId) {
        SysRoleEntity role = this.sysRoleService.selectById(roleId);

        // 查询角色对应的菜单
        List<Long> menuIdList = this.sysRoleMenuService.queryMenuIdList(roleId);
        role.setMenuIdList(menuIdList);

        // 查询角色对应的部门
        List<Long> deptIdList = this.sysRoleDeptService.queryDeptIdList(new Long[]{roleId});
        role.setDeptIdList(deptIdList);

        return R.ok().put("role", role);
    }

    /**
     * 角色列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:role:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = this.sysRoleService.queryPage(params);
        return R.ok(page);
    }

    /**
     * 保存角色
     */
    @SysLog("保存角色")
    @RequestMapping("/save")
    @RequiresPermissions("sys:role:save")
    public R save(SysRoleEntity role) {
        ValidatorUtils.validateEntity(role);

        this.sysRoleService.save(role);

        return R.ok();
    }

    /**
     * 角色列表
     */
    @RequestMapping("/select")
    // @RequiresPermissions("sys:role:select")
    public R select() {
        Map<String, Object> params = new HashMap<>();
        List<SysRoleEntity> list = this.sysRoleService.selectCustomList(params);

        return R.ok().put("list", list);
    }

    /**
     * 跳转至用户编辑页面
     *
     * @param roleId
     * @return
     */
    @RequestMapping("/toEdit/{roleId}")
    public ModelAndView toEdit(@PathVariable("roleId") Long roleId) {
        SysRoleEntity role = this.sysRoleService.selectById(roleId);

        // 查询角色所属的部门
        if (!ObjectUtils.isEmpty(role.getDeptId()) && role.getDeptId().intValue() > 0) {
            SysDeptEntity sysDeptEntity = this.sysDeptService.selectById(role.getDeptId());
            role.setDeptName(sysDeptEntity.getName());
        }

        // 查询角色对应的菜单
        List<Long> menuIdList = this.sysRoleMenuService.queryMenuIdList(roleId);
        role.setMenuIdList(menuIdList);

        // 查询角色对应的部门
        List<Long> deptIdList = this.sysRoleDeptService.queryDeptIdList(new Long[]{roleId});
        role.setDeptIdList(deptIdList);
        ModelAndView modelAndView = new ModelAndView("modules/sys/role/role_edit");
        modelAndView.addObject("role", role);
        return modelAndView;
    }

    /**
     * 修改角色
     */
    @SysLog("修改角色")
    @RequestMapping("/update")
    @RequiresPermissions("sys:role:update")
    public R update(SysRoleEntity role) {
        ValidatorUtils.validateEntity(role);
        this.sysRoleService.update(role);
        return R.ok();
    }

    public R validHasPerms(@RequestParam(value = "perms[]") String[] perms) {
        List<String> permList = Arrays.asList(perms);
        Map<String, Integer> result = new HashMap<>();
        if (this.getUserId().intValue() != Constant.SUPER_ADMIN) {
            result.put("isAdmin", Constant.YesOrNo.NO.getValue());
            List<Long> roleIdList = this.getUser().getRoleIdList();
            if (!ObjectUtils.isEmpty(roleIdList)) {
                Set<Long> menuIdSet = new HashSet<>();
                for (Long roleId : roleIdList) {
                    List<Long> menuIds = this.sysRoleMenuService.queryMenuIdList(roleId);
                    menuIdSet.addAll(menuIds);
                }
                List<SysMenuEntity> menuList = this.sysMenuService.selectBatchIds(menuIdSet);
                if (!ObjectUtils.isEmpty(menuList)) {
                    for (String perm : permList) {
                        boolean hasPerm = false;
                        for (SysMenuEntity item : menuList) {
                            if (hasPerm) {
                                break;
                            }
                            if (item.getPerms().contains(perm)) {
                                hasPerm = true;
                                result.put(perm, Constant.YesOrNo.YES.getValue());
                            }
                        }
                    }
                }
            }
        } else {
            result.put("isAdmin", Constant.YesOrNo.YES.getValue());
        }
        return R.ok().put("result", result);
    }

    /**
     * 查看角色名称
     */
    @RequestMapping("/findRoleName")
    public R findRoleName() {
        Long userId = this.getUserId();
        List<SysRoleEntity> sysRoleEntityList = this.sysRoleService.findRoleName(userId);
        List<String> name = new ArrayList<>();
        for (SysRoleEntity sysRoleEntity : sysRoleEntityList) {
            name.add(sysRoleEntity.getRoleName());
        }
        return R.ok(name);
    }


}
